package com.example.seakdreamandroid.sleep;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;

import androidx.annotation.NonNull;

import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.MainActivity;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.Result;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.sleep.adapter.ClockAdapter;
import com.example.seakdreamandroid.sleep.entity.ClockInfo;
import com.example.seakdreamandroid.sleep.util.MediaUtil;
import com.example.seakdreamandroid.sleep.util.Utility;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AlarmClockAndPrompt extends Activity {

    private ListView lvAlarmList;
    private FloatingActionButton btnAddAlarm;
    private ImageButton imgBtnReturnSleep;
    private List<ClockInfo> dataList = new ArrayList<>();
    private ClockAdapter clockAdapter,promptAdapter;
    private final int REFRESH = 1;
    private List<ClockInfo> list = new ArrayList<>();
    private CountDownTimer countDownTimer;
    private User user;

    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理消息
            switch (msg.what){
                case REFRESH:
                    //刷新ListView
                    Utility.setListViewHeightBasedOnChildren(lvAlarmList);
                    clockAdapter.notifyDataSetChanged();
                    break;
            }
            //闹钟什么时候响
            list= (List<ClockInfo>) msg.obj;
            for (int i = 0; i < list.size(); i++) {
                //闹钟开启
                if (list.get(i).getIfOpen() == 1) {
                    //闹钟的时间
                    int hour = Integer.valueOf(list.get(i).getTime().split(":")[0]);
                    int minute = Integer.valueOf(list.get(i).getTime().split(":")[1]);
                    if (countDownTimer != null) {
                        countDownTimer.cancel();
                    }
                    if (list.get(i).getRepeatSituation().equals( "只响一次")) {
                        oneTimeRing(i,hour,minute);
                    }
                    else if (list.get(i).getRepeatSituation().equals("每天")) {
                        dateRing(hour,minute);
                    } else {
                        String[] split = list.get(i).getRepeatSituation().split(",");
                        for (int j = 0; j < split.length; j++) {
                            if (split[j].equals("周一")) {
                                if (String.valueOf(new Date().getDay()).equals( "1")) {
                                    dateRing(hour,minute);
                                }
                            } else if (split[j].equals("周二")) {
                                if (String.valueOf(new Date().getDay()).equals( "2")) {
                                    dateRing(hour,minute);
                                }
                            } else if (split[j].equals("周三")) {
                                if (String.valueOf(new Date().getDay()).equals("3")) {
                                    dateRing(hour,minute);
                                }
                            }else if (split[j].equals("周四")) {
                                if (String.valueOf(new Date().getDay()).equals( "4")) {
                                    dateRing(hour,minute);
                                }
                            }else if (split[j].equals("周五")) {
                                if (String.valueOf(new Date().getDay()).equals( "5")) {
                                    dateRing(hour,minute);
                                }
                            }else if (split[j].equals("周六")) {
                                if (String.valueOf(new Date().getDay()).equals( "6")) {
                                    dateRing(hour,minute);
                                }
                            }else if (split[j].equals("周日")) {
                                if (String.valueOf(new Date().getDay()).equals( "0")) {
                                    dateRing(hour,minute);
                                }
                            }
                        }
                    }
                }
            }
        }
    };
//每天都响
    private void dateRing(int hourSet, int minuteSet) {
        new HandlerThread("TestThread2") {
            protected void onLooperPrepared() {
                while(true) {
                    Date date = new Date();
                    if ((date.getHours() + ":" + date.getMinutes()).equals(hourSet+":"+minuteSet)) {
                        MediaUtil.playRing(AlarmClockAndPrompt.this);
                        close();
                        break;
                    }
                }
            }
        }.start();
    }
//只响一次
    private void oneTimeRing(int i, int hourSet,int minuteSet) {
        //设定的响铃时间
        Date date = new Date();
        date.setHours(hourSet);
        date.setMinutes(minuteSet);
        int seconds = date.getSeconds();
        if (new Date().getHours() < hourSet || (new Date().getHours()==hourSet && new Date().getMinutes() < minuteSet)) {
            handle(i,(date.getTime() - System.currentTimeMillis()-seconds*1000) / 1000);
        }else if(new Date().getHours()>hourSet || (new Date().getHours()==hourSet && new Date().getMinutes()>minuteSet)){
            int date1 = date.getDate()+1;
            date.setDate(date1);
            handle(i,(date.getTime() - System.currentTimeMillis()-seconds*1000) / 1000);
        }
    }

    private void handle(int i,long l) {
        new HandlerThread("TestThread") {
            protected void onLooperPrepared() {
                CountDownTimer countDownTimer = new CountDownTimer(1000L * (l), 1000L) {
                    @Override
                    public void onTick(long l) {
                        // your logic for tick
                        long minute = l / (1000 * 60); //单位分
                        long second = (l - minute * (1000 * 60)) / 1000;//单位秒
                    }

                    @Override
                    public void onFinish() {
                        MediaUtil.playRing(AlarmClockAndPrompt.this);
                        //关闭闹钟
                        close();
                    }
                };
                countDownTimer.start();
            }
        }.start();
    }

    private void close() {
        AlertDialog.Builder builder = new AlertDialog.Builder(AlarmClockAndPrompt.this);
        builder.setTitle("关闭闹钟")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MediaUtil.stopRing();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_clock_and_prompt);

        getViews();
        getDate();
        initView();
        setListener();

//        for (int i = 0; i < initDataSource().size(); i++) {
//            int hour = Integer.valueOf(initDataSource().get(i).getTime().split(":")[0]);
//            int minute = Integer.valueOf(initDataSource().get(i).getTime().split(":")[1]);
//            if (initDataSource().get(i).getIfOpen() == 1) {
//                dateRing(hour,minute);
//            }
//        }
    }

    private void setListener() {
        //给ListView的监听器
        lvAlarmList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //跳转
                Intent intent = new Intent(AlarmClockAndPrompt.this,AlarmItemDetail.class);
                Bundle bundle = new Bundle();
                ClockInfo clockInfo = dataList.get(i);
                bundle.putSerializable("alarm", clockInfo);
                bundle.putInt("flag",1);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
//        lvPromptList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                //跳转
//                Intent intent = new Intent(AlarmClockAndPrompt.this,AlarmItemDetail.class);
//                Bundle bundle = new Bundle();
//                ClockInfo clockInfo = initDataSource().get(i);
//                bundle.putSerializable("alarm", clockInfo);
//                bundle.putInt("flag",1);
//                intent.putExtras(bundle);
//                startActivity(intent);
//            }
//        });


        //新增
        btnAddAlarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转
                Intent intent = new Intent(AlarmClockAndPrompt.this,AlarmItemDetail.class);
                Bundle bundle = new Bundle();
                ClockInfo add = new ClockInfo();
                bundle.putSerializable("add", add);
                bundle.putInt("flag",3);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        //返回上个页面
        imgBtnReturnSleep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AlarmClockAndPrompt.this, MainActivity.class);
                intent.putExtra("id",1);
                startActivity(intent);
            }
        });
    }

    private void getDate() {
        user = (User) getApplication();
        String URL = Constant.BASE_URL+ "clock/findClockInfo?userId="+ user.getUserId();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(URL)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("onFailure", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                Result result = gson.fromJson(string, new TypeToken<Result<List<ClockInfo>>>(){}.getType());
                List<ClockInfo> clockInfos = (List<ClockInfo>) result.getData();
                dataList.addAll(clockInfos);
                //更新界面
                Message message = new Message();
                message.what = REFRESH;
                message.obj= dataList;
                myHandler.sendMessage(message);
            }
        });
    }

    private void initView(){
        clockAdapter = new ClockAdapter(
                this,
                dataList,
                R.layout.alarm_clock_item
        );
        lvAlarmList.setAdapter(clockAdapter);

//        promptAdapter = new ClockAdapter(
//                this,
//                initDataSource(),
//                R.layout.prompt_clock_item
//        );
//        lvPromptList.setAdapter(promptAdapter);
//        Utility.setListViewHeightBasedOnChildren(lvPromptList);

    }


//    private List<ClockInfo> initDataSource() {
//        List<ClockInfo> list = new ArrayList<>();
//
//        ClockInfo sleep = new ClockInfo();
//        sleep.setMemo("就寝提示");
//        sleep.setTime("23:00");
//        list.add(sleep);
//
//        ClockInfo nap = new ClockInfo();
//        nap.setMemo("小憩提示");
//        nap.setTime("13:00");
//        list.add(nap);
//
//        ClockInfo beforeSleep = new ClockInfo();
//        beforeSleep.setMemo("睡前仪式提醒");
//        beforeSleep.setTime("22:00");
//        list.add(beforeSleep);
//
//        return list;
//    }



    private void getViews() {
        lvAlarmList = (ListView) findViewById(R.id.lv_alarmList);
//        lvPromptList = (ListView)findViewById(R.id.lv_prompt);
        btnAddAlarm = (FloatingActionButton) findViewById(R.id.btn_addAlarm);
        imgBtnReturnSleep = findViewById(R.id.img_btn_return_sleep);
    }

}
